﻿using System;
using System.IO;
using System.Text;

namespace chromium.Utils
{
    public class XorEncryptor
    {
        private byte key;

        public XorEncryptor()
        {
            var keyRandom = new Random();
            key = (byte)keyRandom.Next(256);
        }

        public byte Key
        {
            get { return key; }
            set { key = value; }
        }

        public void Encrypt(byte[] value)
        {
            Encrypt(value, 0, value.Length);
        }

        public void Encrypt(byte[] value, int offset, int len)
        {
            for (int i = offset; i < offset + len; i++)
            {
                value[i] ^= key;
            }
        }
    }

    public class BlockMemoryStream : MemoryStream
    {
        private readonly XorEncryptor ep = new XorEncryptor();
        private bool keySpecify;

        public BlockMemoryStream(int capacity)
            : base(capacity)
        {
        }

        public void WriteBlock(string value)
        {
            byte[] block = Encoding.ASCII.GetBytes(value);
            WriteBlock(block);
        }

        public void WriteBlock(byte[] block)
        {
            if (block == null)
                return;
            WriteBlock(BitConverter.GetBytes(block.Length), 0, 4);
            WriteBlock(block, 0, block.Length);
        }

        public void WriteBlock(byte[] array, int offset, int count)
        {
            if (!keySpecify)
            {
                keySpecify = true;
                WriteByte(ep.Key);
            }

            ep.Encrypt(array, offset, count);

            Write(array, offset, count);
        }
    }
}